package com.kanshu.ksgb.fastread.doudou.common.business.ad

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.Point
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.ak.torch.shell.TorchAd
import com.ak.torch.shell.base.TorchAdLoaderListener
import com.ak.torch.shell.base.TorchAdSpace
import com.ak.torch.shell.nati.TorchNativeAd
import com.ak.torch.shell.player.TorchPlayer
import com.ak.torch.shell.player.TorchVideoAdPlayer
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean
import com.kanshu.ksgb.fastread.doudou.common.imageloader.GlideBitmapLoadingListener
import com.kanshu.ksgb.fastread.doudou.common.imageloader.GlideImageLoader
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils
import com.kanshu.ksgb.fastread.doudou.common.util.JsonUtils
import com.kanshu.ksgb.fastread.doudou.common.util.Utils
import java.util.*


/**
 * Title:
 * Description:
 * Copyright: Copyright(c)2018
 * Company: 看书网
 * CreateTime: 2018/5/20 17:14
 *
 * @author EvanHe
 * @version 3.0
 */
class Ad360Utils {

    companion object {
        private var player: TorchVideoAdPlayer? = null

        fun fetchAd(activity: Activity, container: ViewGroup?, adConfig: ADConfigBean, adStyle: Int, layout: Int, adListener: BaseAdListener?) {
            var adContainer = container ?: FrameLayout(activity)
            val adSpace = TorchAdSpace(adConfig.ad_position_id)
            adSpace.setAdNum(1)
            val mNativeAdLoader = TorchAd.getNativeAdLoader(activity.application.applicationContext, object : TorchAdLoaderListener<TorchNativeAd> {
                override fun onAdLoadSuccess(list: MutableList<TorchNativeAd>?) {
                    if (!Utils.isEmptyList(list)) {
                        val ad360Bean = JsonUtils.json2BeanByFastJson(list!![0].content.toString(), Ad360Bean::class.java)
                        Log.i("Ad360Utils", ad360Bean.toString())
                        var title: TextView? = null
                        var desc: TextView? = null
                        var imgView1: ImageView? = null
                        var imgView2: ImageView? = null
                        var imgView3: ImageView? = null
                        val imageView: ImageView? = when (adStyle) {
                            AdStyleBean.BOOK_COVER_STYLE -> {
                                adContainer = LayoutInflater.from(activity).inflate(layout, adContainer, false) as ViewGroup
                                title = adContainer.findViewById(R.id.book_title) as TextView
                                desc = adContainer.findViewById(R.id.desc) as TextView?
                                adContainer.findViewById(R.id.cover) as ImageView
                            }
                            AdStyleBean.BANNER_STYLE -> {
                                val view = View.inflate(activity, R.layout.layout_360_banner_ad, null) as View
                                val adImg = view.findViewById(R.id.ad_img) as ImageView
                                val width = DisplayUtils.getScreenWidth(activity)
                                val height = width * (90 / 728.0)
                                val lp = FrameLayout.LayoutParams(width, height.toInt())
                                adImg.layoutParams = lp
                                AdUtils.destroyAd(adContainer)
                                adContainer.removeAllViews()
                                adContainer.addView(view)
                                adImg
                            }
                            AdStyleBean.IMAGE_TEXT_STYLE -> {
                                val view = View.inflate(activity, R.layout.layout_360_ad_container, null) as ViewGroup
                                val icon = view.findViewById(R.id.tv_ad_logo) as ImageView
                                title = view.findViewById(R.id.ad_360_title) as TextView
                                if (!TextUtils.isEmpty(ad360Bean.logo)) {
                                    icon.visibility = View.VISIBLE
                                    GlideImageLoader.load(ad360Bean.logo, icon)
                                }
                                val width = DisplayUtils.getScreenWidth(activity) - DisplayUtils.dip2px(activity, 28f)
                                val height = width * (9 / 16.0)
                                val lp = FrameLayout.LayoutParams(width, height.toInt())
                                val imageView = view.findViewById<ImageView>(R.id.ad_chapter_container)
                                imgView1 = view.findViewById(R.id.img_view1)
                                imgView2 = view.findViewById(R.id.img_view2)
                                imgView3 = view.findViewById(R.id.img_view3)
                                imageView.layoutParams = lp
                                AdUtils.destroyAd(adContainer)
                                adContainer.removeAllViews()
                                adContainer.addView(view)
                                imageView
                            }
                            else -> {
                                null
                            }
                        }
                        title?.text = ad360Bean.title ?: adConfig.title ?: ""
                        desc?.text = ad360Bean.desc ?: adConfig.description ?: ""
                        if (list[0].hasVideo()) {
                            player = getPlayer(activity, list[0].key)
                            if (player != null) {
                                val viewGroup = player!!.ui.parent as ViewGroup
                                viewGroup.removeView(player!!.ui)
                                adContainer.addView(player!!.ui)
                                list[0].onAdShowed(adContainer)
                                adListener?.onAdLoadSucceeded(getRootView(adContainer))
                                AdUtils.pVUVAd(AdPresenter.AD_SHOW, adConfig)
                            } else {
                                if (TextUtils.isEmpty(ad360Bean.contentimg)) {
                                    imageView?.visibility = View.GONE
                                    val imageViews = arrayListOf(imgView1, imgView2, imgView3)
                                    bindSmallImage(ad360Bean, list[0], activity, adContainer, imageViews, adStyle, layout, adConfig, adListener)
                                } else {
                                    imageView?.visibility = View.VISIBLE
                                    bindImage(list[0], activity, adContainer, imageView, adStyle, layout, adConfig, adListener)
                                }
                            }
                        } else {
                            if (TextUtils.isEmpty(ad360Bean.contentimg)) {
                                imageView?.visibility = View.GONE
                                val imageViews = arrayListOf(imgView1, imgView2, imgView3)
                                bindSmallImage(ad360Bean, list[0], activity, adContainer, imageViews, adStyle, layout, adConfig, adListener)
                            } else {
                                imageView?.visibility = View.VISIBLE
                                bindImage(list[0], activity, adContainer, imageView, adStyle, layout, adConfig, adListener)
                            }
                        }
                    }
                }

                override fun onAdLoadFailed(i: Int, s: String?) {
                    Log.i("Ad360Utils", "onAdLoadFailed code: $i  msg: $s")
                    // adListener?.onAdLoadFailed()
                    AdUtils.fetchAdFailed(activity, adContainer, adConfig, adStyle, layout, adListener)
                }
            }, adSpace)
            adContainer.tag = mNativeAdLoader
            mNativeAdLoader?.loadAds()
        }

        fun bindSmallImage(ad360Bean: Ad360Bean, itemAd: TorchNativeAd, activity: Activity, adContainer: ViewGroup, imageViews: ArrayList<ImageView?>, adStyle: Int, layout: Int, adConfig: ADConfigBean, adListener: BaseAdListener?) {
            imageViews.forEachIndexed { index, item ->
                if (index >= ad360Bean.imgs.size) return@forEachIndexed
                ad360Bean.imgs?.let {
                    GlideImageLoader.load(it[index].url, item, GlideImageLoader.getEmptyConfig())
                }
            }
            itemAd.onAdShowed(adContainer)
            AdUtils.pVUVAd(AdPresenter.AD_SHOW, adConfig)
            adListener?.onAdLoadSucceeded(adContainer)
            bindClickEvent(itemAd, false, activity, adContainer, adConfig, adListener)
        }

        private fun bindImage(itemAd: TorchNativeAd, activity: Activity, adContainer: ViewGroup, imageView: ImageView?, adStyle: Int, layout: Int, adConfig: ADConfigBean, adListener: BaseAdListener?) {
            if (imageView == null) {
                AdUtils.fetchAdFailed(activity, adContainer, adConfig, adStyle, layout, adListener)
                return
            }
            GlideImageLoader.load(itemAd.content.optString("contentimg"), imageView, GlideImageLoader.getEmptyConfig(), object : GlideBitmapLoadingListener {
                override fun onSuccess(bitmap: Bitmap) {
                    Log.i("Ad360Utils", "图片加载成功：" + itemAd.content.optString("contentimg"))
                    /* when (adStyle) {
                         AdStyleBean.SPLASH_STYLE, AdStyleBean.BANNER_STYLE ->{
                             itemAd.onAdShowed(imageView)
                             AdUtils.pVUVAd(AdPresenter.AD_SHOW, adConfig)
                         }
                     }*/
                    itemAd.onAdShowed(imageView)
                    AdUtils.pVUVAd(AdPresenter.AD_SHOW, adConfig)
                    adListener?.onAdLoadSucceeded(adContainer)
                    bindClickEvent(itemAd, false, activity, adContainer, adConfig, adListener)
                }

                override fun onError() {
                    Log.i("Ad360Utils", "图片加载失败：" + itemAd.content.optString("contentimg"))
                    AdUtils.fetchAdFailed(activity, adContainer, adConfig, adStyle, layout, adListener)
                }
            })
        }

        private var downPoint: Point? = null
        private var upPoint: Point? = null

        private fun bindClickEvent(itemAd: TorchNativeAd, fromVideo: Boolean, activity: Activity, adContainer: ViewGroup, adConfig: ADConfigBean, adListener: BaseAdListener?) {
            if (fromVideo) {
                //播放器内部已经处理点击，开发者无需额外处理点击
            } else {
                adContainer.setOnTouchListener({ _, event ->
                    if (event.action == MotionEvent.ACTION_DOWN) {
                        downPoint = Point(event.x.toInt(), event.y.toInt())
                    } else if (event.action == MotionEvent.ACTION_UP) {
                        upPoint = Point(event.x.toInt(), event.y.toInt())
                    }
                    false
                })

                adContainer.setOnClickListener {
                    itemAd.onAdClick(activity, it, downPoint, upPoint)
                    AdUtils.pVUVAd(AdPresenter.AD_CLICK, adConfig)
                    adListener?.onAdClicked()
                }
            }

        }

        //缓存列表中的播放器
        var map = HashMap<String, TorchVideoAdPlayer>()

        fun getPlayer(activity: Activity, key: String): TorchVideoAdPlayer {
            var player: TorchVideoAdPlayer? = map[key]
            if (player == null) {
                player = TorchPlayer.getVideoAdPlayer(activity, key)
                map[key] = player!!
            }
            return player
        }

        /* fun destroyPlayers() {
             for (player in map.values) {
                 player.destroy()
             }
             map.clear()
         }*/
    }
}